#pragma once

#include <iostream>
#include <unistd.h>
#include <string.h>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"

enum{
    SOCKET_ERR=2,
    BIND_ERR,
    LISTEN_ERR
};

const int backlog = 10;


// 套接字封装
class MySocket{
public:
    MySocket()
    :_sockfd(0)
    {}

    ~MySocket()
    {}

public:
    // 创建套接字
    void Socket(){
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(_sockfd < 0){
            mylog(Fatal, "socket error, errno: %d, strerror: %s", errno, strerror(errno));
            exit(SOCKET_ERR);
        }

        // 防止偶发性的服务器无法进行立即重启                                           
        int opt = 1;
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
    }

    // 绑定套接字
    void Bind(const uint16_t &port){
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;

        if(bind(_sockfd, (const struct sockaddr *)&local, sizeof(local)) < 0){
            mylog(Fatal, "bind error, errno: %d, strerror: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
    }

    // 监听
    void Listen(){
        if(listen(_sockfd, backlog) < 0){
            mylog(Fatal, "listen error, errno: %d, strerror: %s", errno, strerror(errno));
            exit(LISTEN_ERR);
        }
    }

    // 获取客户端连接请求  输出型参数获取客户端的IP地址和端口号
    int Accept(std::string *clientip, uint16_t *clientport){
        struct sockaddr_in client;
        socklen_t len = sizeof(client);

        int newfd = accept(_sockfd, (struct sockaddr *)&client, &len);
        if(newfd < 0){
            mylog(Warning, "accept error, errno: %d, strerror: %s", errno, strerror(errno));
            return -1;
        }

        char ip[64];
        inet_ntop(AF_INET, &client.sin_addr, ip, sizeof(ip));
        *clientip = ip;
        *clientport = ntohs(client.sin_port);

        return newfd;
    }

    // 客户端发送请求连接服务器
    bool Connect(const std::string &serverip, const uint16_t &serverport){
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(serverport);
        inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));

        int n = connect(_sockfd, (const struct sockaddr *)&server, sizeof(server));
        if(n < 0){
            std::cerr << "connect error, errno: " << errno << " strerror: " << strerror(errno) << std::endl;
            return false;
        }
        return true;
    }

    // 关闭文件描述符
    void Close(){
        close(_sockfd);
    }

    // 获取文件描述符
    int Fd(){
        return _sockfd;
    }

private:
    int _sockfd;
};